package com.fc.mall.mongo.dao;

import com.fc.mall.mongo.model.MongoSequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

@Component
public class MongoSequenceRepositoryImpl implements MongoSequenceRepositoryCustom {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public Long nextValue(String sequenceName) {
        Criteria criteria = where("name").is(sequenceName);

        Update update = new Update().inc("value", 1);

        MongoSequence seq = mongoTemplate.findAndModify(query(criteria), update, new FindAndModifyOptions().returnNew(true), MongoSequence.class);
        if (seq != null) {
            return seq.getValue();
        } else {
            return null;
        }
    }

    public void initializeSequence(String sequenceName) {
        Criteria criteria = where("name").is(sequenceName);

        MongoSequence seq = mongoTemplate.findOne(query(criteria), MongoSequence.class);
        if (seq == null) {
            seq = new MongoSequence();
            seq.setName(sequenceName);
            seq.setValue(0);
            mongoTemplate.save(seq);
        }
    }
}
